package com.openNetty.server.main;

import com.openNetty.common.system.FileUtils;
import com.openNetty.common.system.IOUtil;
import com.openNetty.common.system.LoggerUtil;
import com.openNetty.common.utils.QuartzManager;
import com.openNetty.server.timertask.DownSqlDataTask;


import java.io.*;
import java.net.URL;

import static com.openNetty.common.bean.MainContents.KEY;
import static com.openNetty.common.bean.MainContents.CONFIG_FILE;
import static com.openNetty.common.bean.MainContents.DOWNFILEDATA;

public class ServerStart {
    private static LoggerUtil logger;

    /**
     * 资源初始化数据
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        init();// 初始化配置文件数据
        startTimerTask(); // 加载定时任务启动
        /**
         * 此类为预留配置，作为HTTP WEB容器使用
         NettyContainer.start();
         */
        logger.info("******SQLBACK-SERVER IS STARTED******");
    }

    /**
     * 启动定时任务管理器
     */
    private static void startTimerTask() {
        logger.info("启动定时任务列表中");
        // 取消quartz检查更新
        System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true");
        logger.info("加载文件下载任务");
        QuartzManager.addJob("文件定时下载任务", DownSqlDataTask.class, Global.properties.getProperty(DOWNFILEDATA));
        logger.info("任务列表启动完成");
    }

    /**
     * 初始化配置文件
     *
     * @throws IOException
     */
    public static void init() throws IOException {

        URL root = null;
        try {
            root = new File(IOUtil.getCurrentExecutePath(ServerStart.class)).getParentFile().getParentFile().toURI().toURL();
            LoggerUtil.build(FileUtils.mergePath(root.getPath(), "config"));
            logger = LoggerUtil.getLogger(ServerStart.class);
            logger.info("load Log properties success");

        } catch (Exception e) {
            System.out.println(System.currentTimeMillis() + " [ERROR] Server start failed. logger can not init.please check log config file.");
            e.printStackTrace();
        }

        String nodePath = root.getPath() + CONFIG_FILE;
        // 加载服务器属性配置文件
        FileInputStream inputStream = new FileInputStream(nodePath);
        Global.properties.load(inputStream);
        logger.info("load back properties success");

        String keyPath = root.getPath() + KEY;
        getKey(keyPath);
    }

    /**
     * 加载秘钥文件
     *
     * @param keyPath
     * @throws IOException
     */
    public static void getKey(String keyPath) throws IOException {
        logger.info("开始加载秘钥路径：" + keyPath);
        File key = new File(keyPath);
        if (key.isDirectory()) {
            File[] files = key.listFiles();
            for (File fileIndex : files) {
                //如果这个文件是目录，则进行递归搜索
                if (fileIndex.isDirectory()) {
                    getKey(fileIndex.getPath());
                } else {
                    //如果文件是秘钥进行存储
                    receiveSecret(fileIndex);
                }
            }
        }
    }

    public static void receiveSecret(File keyFile) throws IOException {
        try {
            InputStream inputStream = new FileInputStream(keyFile);//文件内容的字节流
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream); //得到文件的字符流
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader); //放入读取缓冲区
            String readd = "";
            StringBuffer stringBuffer = new StringBuffer();
            while ((readd = bufferedReader.readLine()) != null) {
                stringBuffer.append(readd);
            }
            inputStream.close();
            String keystr = stringBuffer.toString();
            Global.keyMap.put(String.valueOf(keyFile.getName().hashCode()), keystr);
        } catch (Exception e) {

            logger.error(e);
            throw new IOException("秘钥文件加载失败");
        }
    }
}
